package com.dhcc.bpm.common.utils;

import io.swagger.parser.OpenAPIParser;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.parser.core.models.ParseOptions;
import org.openapitools.codegen.ClientOptInput;
import org.openapitools.codegen.DefaultGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.List;


public class SdkGenerateUtil {
	private static final Logger log = LoggerFactory.getLogger(SdkGenerateUtil.class);


	/*
	 * @Description 生成SDK
	 * @params service 服务名称
	 * @params url 路径
	 *
	 */
	public static boolean generateByUrl(String service, String yarm, String sdkPath) throws IOException {
		String artifactId = service + "-client";
		File output = new File(sdkPath);
		if (!output.exists()) {
			output.mkdirs();
		}
		log.info("output dir is :" + output.toString());
		log.info("service id is {}, location is {}", service, yarm);
		OpenAPI openAPI = new OpenAPIParser().readLocation(yarm, null, new ParseOptions()).getOpenAPI();

		JavaClientGenerateUtil codegen = new JavaClientGenerateUtil(service);
		codegen.setArtifactId(artifactId);
		codegen.setOutputDir(output.getAbsolutePath());
		codegen.setArtifactUrl(yarm);

		ClientOptInput input = new ClientOptInput();
		input.openAPI(openAPI);
		input.config(codegen);

		DefaultGenerator generator = new DefaultGenerator();
		List<File> files = generator.opts(input).generate();
		if (null == files) {
			log.info("generate fail");
			return false;
		} else {
			log.info("generate success, please see:" + output.getAbsolutePath());
			//将生成的sdk文件源码进行压缩
			ZipUtils.toZip(sdkPath, sdkPath + ".zip", true);
			//压缩文件完成后删除源文件目录
			ZipUtils.delFiles(output);
			return true;
		}
	}
	/*
	 * @Description 生成SDK
	 * @params service 服务名称
	 * @params url 路径
	 *
	 */
	public static boolean generateByContent(String service, String model, String yarmContent, String sdkPath) throws IOException {
		String artifactId = service + "-client";
		File output = new File(sdkPath);
		if (!output.exists()) {
			output.mkdirs();
		}
		log.info("output dir is :" + output.toString());
		log.info("service id is {}, location is {}", service, yarmContent);
		OpenAPI openAPI = new OpenAPIParser().readContents(yarmContent, null, new ParseOptions()).getOpenAPI();

		JavaClientGenerateUtil codegen = new JavaClientGenerateUtil(model);
		codegen.setArtifactId(artifactId);
		codegen.setOutputDir(output.getAbsolutePath());

		ClientOptInput input = new ClientOptInput();
		input.openAPI(openAPI);
		input.config(codegen);

		DefaultGenerator generator = new DefaultGenerator();
		List<File> files = generator.opts(input).generate();
		if (null == files) {
			log.info("generate fail");
			return false;
		} else {
			log.info("generate success, please see:" + output.getAbsolutePath());
			return true;
		}
	}

}
